package com.jeehentor.filter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import com.jeehentor.common.vo.LoggerMessage;
import com.jeehentor.config.webSocket.LoggerQueue;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.util.Date;

/**
 * @Description : 获取logback的日志，塞入日志队列中
 * 定义Logfilter拦截输出日志
 * @Author : wzd
 * @Date : 2024/4/30 17:51
 * @Version : 1.0
 **/
@Service
public class LogFilter extends Filter<ILoggingEvent>
{
    @Override
    public FilterReply decide(ILoggingEvent event)
    {
        StringBuilder exception = new StringBuilder();
        IThrowableProxy iThrowableProxy1 = event.getThrowableProxy();
        if (iThrowableProxy1 != null)
        {
            exception = new StringBuilder("\n" + iThrowableProxy1.getClassName() + " " + iThrowableProxy1.getMessage() + "\n");
            for (int i = 0; i < iThrowableProxy1.getStackTraceElementProxyArray().length; i++)
            {
                exception.append(iThrowableProxy1.getStackTraceElementProxyArray()[i].toString()).append("\n");
            }
        }
        LoggerMessage loggerMessage = new LoggerMessage(event.getMessage(), DateFormat.getDateTimeInstance().format(new Date(event.getTimeStamp())), event.getThreadName(), event.getLoggerName(),
                event.getLevel().levelStr, exception.toString(), "");
        LoggerQueue.getInstance().push(loggerMessage);
        return FilterReply.ACCEPT;
    }
}